<?php

class Service_Notification {
    const TYPE_NEW_IDEA = 'idea';
    const TYPE_NEW_COMMENT = 'comment';
    const TYPE_NEW_IDEA_VOTE = 'vote';
    const TYPE_NEW_FOLLOW = 'follow';

    public static function send($type, $recipients, $object) {

        $view_path = Service_Skin::get() . '/notifications/' . $type;
        $data = array(
            'object' => $object,
            'user' => Service_User::current()
        );
        $text = View::factory($view_path, $data)->render();
        $notification = new Model_Notification();
        $notification->recipients = $recipients;
        $notification->text = $text;
        $notification->save();
		self::_incremet_anread($recipients);
    }

	private static function _incremet_anread($recipients) {
		$cond = array(
			'id' => $recipients
		);
		$users = Model_User::get_mapper()->fetch_all($cond);
		foreach ($users as $user) {
			$user->unread_notifications_count +=1;
			$user->save();
		}
		
	}
    public static function send_idea(Model_Post $post) {
        $recipients = array($post->user_id);
        $recipients += $post->followers;
        $recipients = self::_clean_recipients($recipients);
        Service_Notification::send(Service_Notification::TYPE_NEW_IDEA, $recipients, $post);
    }

    public static function send_follow(Model_Post $post) {
        $recipients = array($post->user_id);
        $recipients += $post->followers;
        $recipients = self::_clean_recipients($recipients);
        Service_Notification::send(Service_Notification::TYPE_NEW_FOLLOW, $recipients, $post);
    }

    public static function send_comment(Model_Post $post, Model_Idea $idea) {
        $recipients = array($post->user_id);
        $recipients += $post->followers;
        $recipients[]= $idea->user_id;
        $recipients = self::_clean_recipients($recipients);
        Service_Notification::send(Service_Notification::TYPE_NEW_COMMENT, $recipients, $post);
    }

    public static function send_vote(Model_Post $post, Model_Idea $idea) {
        $recipients = array($post->user_id);
        $recipients += $post->followers;
        $recipients[]= $idea->user_id;
        $recipients += $idea->procontra->extract_field('user_id');

        $recipients = self::_clean_recipients($recipients);
        Service_Notification::send(Service_Notification::TYPE_NEW_IDEA_VOTE, $recipients, $post);
    }

    private static function _clean_recipients($recipients) {

        foreach ($recipients as &$recipient) {
            $recipient = (string) $recipient;
        }
        $recipients = array_unique($recipients);
        if(!Service_User::is_guest()) {
            $recipients = array_diff($recipients, array((string) Service_User::current()->id, ''));
        }
        return $recipients;
    }

}